package com.wangsd.web.mqpay.service;

import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.util.MyBeanUtil;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.web.mqpay.entity.CustomerFlow;
import com.wangsd.web.mqpay.mapper.CustomerFlowMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class CustomerFlowService {
    @Resource
    private CustomerFlowMapper mapper;

    public List<CustomerFlow> selectPage(CustomerFlow queryObj, String code) {
        Query query = new Query();
        if (queryObj.getCustomerId() != null) {
            query.eq("t.customer_id", queryObj.getCustomerId());
        }
        if (StringUtils.isNotBlank(code)) {
            query.likeRight("t2.code", code);
        }
        query.join("join customer t2 on t.customer_id = t2.id");
        List<String> column = Arrays.asList("t.*, t2.name as customerName");
        List<Map<String, Object>> mapList = mapper.listMap(column, query);
        List<CustomerFlow> list = MyBeanUtil.mapListToObjList(mapList, CustomerFlow.class);
        return list;
    }

    public int save(Long customerId, Integer settleAmount) {
        CustomerFlow customerFlow = new CustomerFlow();
        customerFlow.setSettleAmount(settleAmount);
        customerFlow.setCustomerId(customerId);
        customerFlow.setStatus(1);
        return mapper.saveIgnoreNull(customerFlow);
    }

    public int delete(Long id) {
        CustomerFlow customerFlow = mapper.getById(id);
        if (customerFlow.getStatus() == 2){ //提现完成
            throw new BusinessException("不允许删除已完成的记录！");
        }
        return mapper.deleteById(id);
    }

    /**
     * 提现完成
     * @param id
     * @return
     */
    public int complete(Long id) {
        CustomerFlow customerFlow = new CustomerFlow();
        customerFlow.setId(id);
        customerFlow.setStatus(2);
        customerFlow.setCompletedTime(new Date());
        return mapper.updateIgnoreNull(customerFlow);
    }
}
